package J20250121_Dynamic;

/**
 * Created with IntelliJ IDEA.
 * Description: 动态规划39——42
 * User: 王圆豪
 * Date: 2025-01-25
 * Time: 23:45
 */
public class Solution5 {
    //最⻓回⽂⼦序列——https://leetcode.cn/problems/longest-palindromic-subsequence/
    public int longestPalindromeSubseq(String s) {
        int n = s.length();
        int[][] dp = new int[n][n];
        int ret = 0;
        for(int i = n-1; i >= 0; i--){
            for(int j = i; j < n;j++){
                if(s.charAt(i) == s.charAt(j)){
                    if(i == j){
                        dp[i][j] = 1;
                    }else if(i + 1 == j){
                        dp[i][j] = 2;
                    }else{
                        dp[i][j] = dp[i+1][j-1] + 2;
                    }
                    ret = Math.max(dp[i][j], ret);
                }else{
                    dp[i][j] = Math.max(dp[i][j-1],dp[i+1][j]);
                }
            }
        }
        return ret;
    }
    //让字符串成为回⽂串的最⼩插⼊次数——https://leetcode.cn/problems/minimum-insertion-steps-to-make-a-string-palindrome/
    public int minInsertions(String s) {
        int n = s.length();
        int[][] dp = new int[n][n];
        for(int i = n-1; i>=0;i--){
            for(int j = i+1; j < n; j++){
                if(s.charAt(i) == s.charAt(j)){
                    dp[i][j] = dp[i+1][j-1];
                }else{
                    dp[i][j] = Math.min(dp[i+1][j], dp[i][j-1]) + 1;
                }
            }
        }
        return dp[0][n-1];
    }
    //最⻓公共⼦序列——https://leetcode.cn/problems/longest-common-subsequence/description/
    public int longestCommonSubsequence(String text1, String text2) {
        int m = text1.length();
        int n = text2.length();
        int[][] dp = new int[m+1][n+1];
        for(int i = 1; i <= m; i++){
            for(int j = 1; j <= n; j++){
                if(text1.charAt(i-1) == text2.charAt(j-1)){
                    dp[i][j] = dp[i-1][j-1] + 1;
                }else{
                    dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);
                }
            }
        }
        return dp[m][n];
    }
    //不相交的线——https://leetcode.cn/problems/uncrossed-lines/
    public int maxUncrossedLines(int[] nums1, int[] nums2) {
        int m = nums1.length, n = nums2.length;
        int[][] dp = new int[m+1][n+1];
        for(int i = 1; i <= m; i++){
            for(int j = 1; j <= n; j++){
                if(nums1[i-1] == nums2[j-1]){
                    dp[i][j] = dp[i-1][j-1] + 1;
                }else{
                    dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);
                }
            }
        }
        return dp[m][n];
    }
}
